import formidable from "formidable";
import {createTweet} from "~/server/db/tweets.js";
import {uploadToCloudinary} from "~/server/utils/cloudinary.js";
import {createMediaFile} from "~/server/db/mediaFiles.js";
import {tweetTransformer} from "~/server/transformers/tweet.js";

export default defineEventHandler(async (event) => {
    const form = formidable({})

    const response = await  new Promise((resolve,reject)=>{
        form.parse(event.node.req,(err,fields,files)=>{
            if(err){
                reject(err)
            }
            resolve({fields,files})
        })
    })
    const { fields, files } = response
    const userId = event.context?.auth?.user?.id
    const tweetData = {
        text:fields.text[0],
        authorId: userId
    }
    const replyTo = fields.replyTo?.[0]

    if(replyTo && replyTo !== 'null' && replyTo !== 'undefined'){
        tweetData.replyToId = +replyTo
    }
    // 吧文章存到数据库
    const tweet = await createTweet(tweetData)
    // 处理图片和视频
    const filePromises = Object.keys(files).map(async key=>{
        const file = files[key][0]
        const cloudinaryResource = await uploadToCloudinary(file.filepath)
        // 把图片传到 cloudinary（类似oss）上面 然后拿到返回的云端地址信息 ，然后存到数据库中
        return createMediaFile({
            url: cloudinaryResource.secure_url,
            providerPublicId: cloudinaryResource.public_id,
            userId: userId,
            tweetId: tweet.id
        })
    })

    await Promise.all(filePromises)

    return {
        tweet: tweetTransformer(tweet)
    }
})
